package com.ruoyi.web.common.util;

import org.springframework.stereotype.Component;

@Component
public class RetryUtil {

    public interface RetryableTask<T> {
        T execute() throws Exception;
    }

    public static <T> T executeWithRetry(RetryableTask<T> task, int maxRetries, long delayMillis) throws Exception {
        int retryCount = 0;
        Exception lastException = null;

        while (retryCount < maxRetries) {
            try {
                T result = task.execute();
                // 添加对 null 结果的判断
                if (result != null) {
                    return result; // 只有结果不为 null 时才返回成功
                }
                // 如果结果为 null，视为失败，继续重试
            } catch (Exception e) {
                lastException = e;
            }

            retryCount++;
            if (retryCount < maxRetries) {
                try {
                    Thread.sleep(delayMillis);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("重试被中断", ie);
                }
            }
        }

        // 所有重试都失败，抛出异常
        if (lastException != null) {
            throw lastException;
        } else {
            throw new RuntimeException("达到最大重试次数，所有尝试均返回空结果");
        }
    }
}
